#include "flowchart_blck.h"
#include "ui_flowchart_blck.h"
#include <QFileDialog>
#include <QDebug>
#include <QDesktopServices>
flowchart_blck::flowchart_blck(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::flowchart_blck)
{
    ui->setupUi(this);
    //get settings
    QString setting_ini = QApplication::applicationDirPath() + "/user_data/setting.ini";
    settings = new QSettings(setting_ini,QSettings::IniFormat);
    QString flowchart_dir_saved = settings->value("flowchart_dir_saved",QApplication::applicationDirPath() +"/user_data/flowchart_blck").toString();
    ui->ui_lin_dir->setText(flowchart_dir_saved);
    //tree trig
    ui->ui_tree_flow->setEditTriggers(QAbstractItemView::NoEditTriggers);
    tocModelFlow = new QStandardItemModel(0, 1, this);
    // 初始化操作
    on_ui_btm_update_clicked();
}

flowchart_blck::~flowchart_blck()
{
    delete ui;
}

void flowchart_blck::on_ui_btm_dir_clicked()
{
    QString p_dir  = QFileDialog::getExistingDirectory
                            (this,
                             "Please choose an work dir",
                             "");
    if (p_dir.isEmpty())
    {
        qDebug() << "你取消了选择。";
        return;
    }
    ui->ui_lin_dir->setText(p_dir);
    settings->setValue("flowchart_dir_saved",p_dir);
}

void flowchart_blck::on_ui_btm_update_clicked()
{
    // 初始化树状图
    tocModelFlow->clear();
    tocModelFlow->setHorizontalHeaderLabels({"文件导航"});
    ui->ui_tree_flow->setModel(tocModelFlow);
    //加载流程文档
    QStringList filters;
    QString team_name = "*.drawio";
    filters << team_name;
    QDir dir(ui->ui_lin_dir->text());
    if (!dir.exists())
    {
        qDebug() << "目录不存在: " << dir;
        return;
    }
    dir.setNameFilters(filters);
    QStringList fileList = dir.entryList(QDir::Files);
    foreach(const QString &file , fileList)
    {
        QStandardItem * parentItem1 = new QStandardItem(file); //以第一个文件为父节点
        tocModelFlow->appendRow(parentItem1);
    }

}


void flowchart_blck::on_ui_tree_flow_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        QString s_node;
        s_node   = tocModelFlow->data(index,Qt::DisplayRole).toString();
        // 将文件路径转换为QUrl对象
        QString s_file = ui->ui_lin_dir->text() + "/" + s_node;
        QUrl fileUrl = QUrl::fromLocalFile(s_file);
        // 尝试打开文件
        if (QDesktopServices::openUrl(fileUrl)) {
            qDebug() << "文件已成功打开。";
            return;
        } else {
            qDebug() << "无法打开文件。" << s_node;
            //如果打不开目标日志文件
        }
    }
}

